<template>
  <div>
    <!-- 报名浮动导航 -->
    <a-affix :offsetBottom="this.bottom">
      <a-row>
        <a-col :span="24">
          <a-button-group size="large">
            <!-- 领优惠券 -->
            <a-button type="primary" @click="showCoupon" class="btn-coupon" >
              <a-icon type="left" />我要领红包
            </a-button>
            <!-- 线上报名 -->
            <a-button type="primary" @click="showSignUp" class="btn-signup" >
              线上报名
              <a-icon type="right" />
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-affix>
    <!-- 领取红包弹框 v-modal-->
    <a-modal v-model="$store.state.money" @ok="onClose" class="red-packets" footer='' title="" :style="{top:'20px',margin:'60px',padding:0,borderRadius:'12px',overflow:'hidden'}" :bodyStyle="{ padding: 0 }"
>
      <!-- 领取红包 -->
      <div v-if="!open" class="pic" >
        <img class="bg" src="@/assets/redPackets.png" alt="" >
        <img @click="openRedPackets" class="btn-open" src="@/assets/btn_open_redPackets.png" alt="" >
      </div>
      <!-- 已领红包 -->
      <div v-else class="petpackets" >
        <img class="bg" src="@/assets/petRedPackets.png" alt="" >
        <div class="petbox">
          <p class="amount"><span class="rmb">￥</span>{{amount}}</p>
          <a-form :form="form2" layout="vertical" hideRequiredMark @submit="handlePet" class="petform" >
            <a-row :gutter="16">
              <a-col :span="24">
                <a-form-item>
                  <a-input
                    size="large"
                    type='tel'
                    v-decorator="['phonenumber', {rules: [{validator: validatePhone}] }]"
                    placeholder="输入手机号码"
                  />
                </a-form-item>
                <a-button
                  class='btn-pet'
                  size="large"
                  html-type="submit"
                >领取红包</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </div>
    </a-modal>
    <!-- 已领优惠券 -->
    <a-modal
      v-model="$store.state.coupon"
      @ok="onClosed"
      class="red-packets"
      footer=''
      title=""
      :style="{top:'20px',margin:'20px',padding:0,borderRadius:'12px',overflow:'hidden'}"
      :bodyStyle="{ padding: 0 }"
    >
    <!-- <div v-if='discountList.length'> -->
      <div  class="petpackets" v-for="(item,index) in discountList" :key="index">
        <div :class="'stamp stamp01'">
          <div class="par"><p>{{item.discount.companyName}}</p><sub class="sign">￥</sub><span>{{item.discount.money}}</span><sub>优惠券</sub><p>享线下报名新课优惠，可抵现金(不可叠加使用)</p></div>
          <div class="copy">副券<p>2019-08<br>2020-08</p></div>
          <i></i>
        </div>
      </div>
    <!-- </div> -->
    <!-- <div v-else>
      <div class="petpackets02">
        目前没有可以领的优惠券哦！
      </div>
    </div> -->
    </a-modal>
    <!-- 在线报名抽屉 -->
    <a-drawer
      title="在线报名"
      height='auto'
      :placement="placement"
      :closable="false"
      :visible="visibleSignUp"
      @close="onClose"
    >
      <a-form
        :form="form"
        layout="vertical"
        hideRequiredMark
        @submit="handlePay"
      >
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="">
              <a-input
                size="large"
                v-decorator="['phonenumber', {
                  rules: [{validator: validatePhone}]
                }]"
                placeholder="输入手机号码"
              />
            </a-form-item>
            <a-form-item label="">
              <a-input
                size="large"
                v-decorator="['name', {
                  rules: [{ required: true, message: '请输入您的姓名' }]
                }]"
                placeholder="请输入您的姓名"
              />
            </a-form-item>
            <a-form-item>
              <a-alert v-if="infos" :message="infos.name+'：￥'+((infos.payprice)||0)" type="warning" />
            </a-form-item>
            <!-- <a-form-item>
              <a-checkbox-group class="comb-pic" :options="options" @change="onChange" />
            </a-form-item> -->
            <a-button-group
              size="large"
              value="a"
              v-if="infos"
            >
              <a-button
                class='btn-price'
                size="large"
                value='a'
              >合计：￥{{payprice}}</a-button>
              <a-button
                type="primary"
                html-type="submit"
                class="btn-signup"
              >
                支付
              </a-button>
            </a-button-group>
          </a-col>
        </a-row>
      </a-form>
    </a-drawer>
  </div>
</template>
<script>
import { Modal } from 'ant-design-vue'
import { constants } from 'crypto';
// 微信分享api
import wxapi from "@/tools/wxapi.js";
export default {
  data() {
    return {
      discount:null,//未领红包数据
      discountList:null,//已领优惠券列表
      form: this.$form.createForm(this),//领红包表单
      form2: this.$form.createForm(this),//报名交钱表单
      top: 10,
      bottom: 0,
      placement: "bottom",
      visibleSignUp: false,//在线报名弹框
      open: false,//点击了红包
      amount: "00.00",//红包金额
      payprice:0.0,//付款金额
      options :[],//是否选择额外选项
      comb:1,// 1代表付款选项组合1
      combprice:11.11//额外选项金额-写死了
    };
  },
  props: ["infos"],
  mounted(){
    let vo = this;
    let id = vo.$route.query.id,
        url = `backstage/queryDiscount.do?id=${id}`;
    vo.id = id;
    vo.ajax
    .get(url)
    .then(res => {
      console.log(res.data);
      if(res.data.discountList){
        vo.$store.commit('onpet', {//设定已领
          isPet:true
        })
        vo.discountList = res.data.discountList;
      }else if(res.data.discount){
        vo.$store.commit('onpet', {//设定没领
          isPet:false
        })
        vo.discount = res.data.discount;
        vo.amount = res.data.discount.money;
      }
    });
  },
  watch:{
    infos(){
      let vo = this;
      vo.payprice  = +vo.infos.payprice; 
      vo.options.push({ label: `￥${vo.combprice}元抢购 ￥111.0 元代金券(仅限购买新课程)`, value: 'active' })
    }
  },
  methods: {
    // 追加额外选项
    onChange(checkedValues) {
      if(checkedValues.length == 1){//选中额外加项
        this.comb = 2;
        this.payprice += +this.combprice;
      }else{
        this.comb = 1;
        this.payprice = +this.infos.payprice;
      }
    },
    // 请求-领优惠券
    showCoupon() {
      let vo = this;
      if(vo.$store.state.isPet){
        let url = `backstage/queryDiscount.do?id=${vo.id}`;
        vo.ajax
        .get(url)
        .then(res => {
          if(res.data.discountList){
            vo.$store.commit('onpet', {//设定已领
              isPet:true
            })
            vo.$store.commit('oncoupon', {//领券弹框
              coupon:true
            })
            vo.discountList = res.data.discountList;
          }
        });
        
      }else{
        vo.$store.commit('onmoney', {//红包弹框
          money:true
        })
      }
    },
    //刚领红包
    openRedPackets() {
      this.open = true;
    },
    //请求-领红包
    handlePet(e) {
      let vo = this;
      e.preventDefault();
      vo.form2.validateFields((err, values) => {
        if (!err) {
          let vo = this,
          url = `backstage/getDiscount.do?id=${vo.infos&&vo.infos.id}&phone=${values.phonenumber}`;
          vo.ajax
          .get(url)
          .then(res => {
            console.log(res);
            if(res.data.flag){//领取成功
              vo.$store.commit('onmoney', {
                money:false
              })
              vo.$store.commit('onpet', {
                isPet:true
              })
              Modal.success({
                title: '红包已领取',
                content: (  // JSX support
                  <div>
                    <br/>
                    <p>再次点击[我要领红包]可查看已领红包</p>
                    <p>已领取红包仅用于线下课程报名</p>
                  </div>
                ),
                okText:'知道了',
                okType:'danger'
              });
            }else{//领取失败
              //vo.visibleCoupon = false;//隐藏红包界面
              vo.$store.commit('onmoney', {
                money:false
              })
              vo.$store.commit('onpet', {
                isPet:false
              })
              Modal.danger({
                title: '红包领取失败',
                content: (  // JSX support
                  <div>
                    <br/>
                    <p>啊呀，红包领取失败,</p>
                    <p>请重新领取！</p>
                  </div>
                ),
                okText:'知道了',
                okType:'danger'
              });
            }
          });
        }
      });
    },
    //抽屉-在线报名
    showSignUp() {
      this.visibleSignUp = true;
    },
    //请求-报名
    handlePay(e) {
      let vo = this;
      e.preventDefault();
      vo.form.validateFields((err, values) => {
        if (!err) {
          const phonenumber = values.phonenumber;
          const name = values.name;

          let url = `pay/pay.do?phonenumber=${phonenumber}&name=${name}&activityid=${vo.infos&&vo.infos.id}&comb=${vo.comb}`;
          vo.ajax
            .get(url)
            .then(res => {
              //调取微信支付接口
              vo.onBridgeReady(res,vo.paySuccess,vo.payError);
            });
        }
      });
    },
    onBridgeReady(res,fn,fn2){
      WeixinJSBridge.invoke( 'getBrandWCPayRequest', {
      
      "appId":res.appId, //公众号名称,由商户传入
      
      "timeStamp":res.timeStamp, //时间戳,自1970年以来的秒数
      
      "nonceStr":res.nonceStr, //随机串
      
      "package":res.packageValue,
      
      "signType":res.signType, //微信签名方式：
      
      "paySign":res.paySign //微信签名
      
      },
      function(res){
        if(res.err_msg == "get_brand_wcpay_request:ok" ) {
          console.log('支付成功');
          //支付成功后跳转的页面
          fn();
          }else if(res.err_msg == "get_brand_wcpay_request:cancel"){
            // fn2
          console.log('支付取消');
          }else if(res.err_msg == "get_brand_wcpay_request:fail"){
          fn2();
          WeixinJSBridge.call('closeWindow');
        } //使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
      })
    },
    //支付成功回调
    paySuccess(res){
      Modal.success({
        title: '支付成功',
        content: (  // JSX support
          <div>
            <br/>
            <p>已经成功购买课程</p>
            <p>请关注合众易成公众号查询订单信息</p>
          </div>
        ),
        okText:'知道了',
        okType:'danger'
      });
    },
    payError(res){
      Modal.danger({
        title: '支付失败',
        content: (  // JSX support
          <div>
            <br/>
            <p>课程支付失败</p>
            <p>请在网络稳定环境中重新支付</p>
          </div>
        ),
        okText:'知道了',
        okType:'danger'
      });
    },
    // 关闭抽屉
    onClose() {
      let vo = this;
      vo.$store.commit('onmoney', {
        money:false
      })
      this.visibleSignUp = false;
    },
    // 关闭已领优惠券
    onClosed() {
      vo.$store.commit('oncoupon', {
        coupon:false
      })
    },
    //校验手机号码
    validatePhone(rule, value, callback){
      let reg = new RegExp('^[1][3,6,4,5,7,8][0-9]{9}$', 'g')
      if (!reg.test(value)) {
        callback('手机号码格式有误')
        return;
      }
      callback()
    }
  }
};
</script>
<style scoped lang="less">
.comb-pic{
  color: #f44336;
}
/* 浮动导航 */
.ant-btn-group {
  width: 100%;
  .btn-coupon,
  .btn-signup,
  .btn-price {
    width: 50%;
  }
  .btn-price {
    color: #ff4d4f;
    background-color: #fff;
    border-color: #ff4d4f;
  }
  .btn-coupon {
    background: #ff9800;
    border-color: #ff9800;
    border-right-color: #ff9800 !important;
  }
  .btn-signup {
    background: #f44336;
    border-color: #f44336;
    border-left-color: #f44336 !important;
  }
}
/* 红包 */
.red-packets {
  .bg {
    width: 100%;
  }
  .btn-open {
    width: 30%;
    position: absolute;
    bottom: 12%;
    left: 35%;
  }
}
/* 领红包*/
.petpackets {
  position: relative;
  .petbox {
    position: absolute;
    top: 28%;
    width: 100%;
    padding: 0 10%;
    text-align: center;
    background: url(/@/assets/petRedPackets02.png) no-repeat top center;
    background-size: 100% auto;
    .amount {
      font-size: 41px;
      color: #ffe2b1;
      width: 100%;
      text-align: center;
      line-height: 1;
      margin-bottom: 3rem;
      .rmb {
        font-size: 37px;
      }
    }
    .petform {
      .btn-pet {
        background: #d9af68;
        border-color: #d9af68;
        color: #fff;
      }
    }
  }
}
/*代金券*/
.stamp {width: 387px;height: 180px;padding: 0 10px;position: relative;overflow: hidden;}
.stamp:before {content: '';position: absolute;top:0;bottom:0;left:10px;right:10px;z-index: -1;}
.stamp:after {content: '';position: absolute;left: 10px;top: 10px;right: 10px;bottom: 10px;box-shadow: 0 0 20px 1px rgba(0, 0, 0, 0.5);z-index: -2;}
.stamp i{position: absolute;left: 20%;top: 45px;height: 190px;width: 390px;background-color: rgba(255,255,255,.15);transform: rotate(-30deg);}
.stamp .par{float: left;padding: 16px 15px;width: 220px;border-right:2px dashed rgba(255,255,255,.3);text-align: left;}
.stamp .par  p{color:#fff;margin-bottom: 0;font-size:13px;}
.stamp .par span{font-size: 46px;color:#fff;margin-right: 5px;}
.stamp .par .sign{font-size: 34px;}
.stamp .par sub{position: relative;top:-5px;color:rgba(255,255,255,.8);}
.stamp .copy{display: inline-block;padding:21px 14px;width:100px;vertical-align: text-bottom;font-size: 30px;color:rgb(255,255,255);}
.stamp .copy p{font-size: 16px;margin-top: 15px;}
.stamp01{background: #F39B00;background-size: 15px 15px;background-position: 9px 3px;/*background: radial-gradient(rgba(0, 0, 0, 0) 0, rgba(0, 0, 0, 0) 5px, #F39B00 5px);*/}
.stamp01:before{background-color:#F39B00;}
.stamp01:last-child{background: #D24161;background-size: 15px 15px;background-position: 9px 3px;/*background: radial-gradient(transparent 0, transparent 5px, #D24161 5px);*/}
.stamp01:last-child:before{background-color:#D24161;}
</style>
